<script setup>
import { defineProps, defineEmits, ref, watch, onMounted, computed } from 'vue'
import coverImg from '@/assets/images/game-cover-1.svg'
import { roomAPI } from '@/api'
import request from '@/utils/request.js'

// 接收房间信息对象（roomId、roomName、status、playerCount、maxPlayers 等）
const props = defineProps({
  room: {
    type: Object,
    required: true,
    default: () => ({})
  }
})

// 向父组件派发选择事件（用于展示房间详情或加入房间）
const emit = defineEmits(['select', 'join'])

// 缓存：避免重复请求房主头像（模块级缓存）
const hostAvatarCache = new Map()
const hostAvatar = ref('')
const memberAvatars = ref([])
const displayedAvatars = computed(() => {
  const arr = (memberAvatars.value || []).filter(Boolean)
  const maxItems = 4
  if (arr.length <= maxItems) return arr
  // 留一个位置给 +N
  return arr.slice(0, maxItems - 1)
})
const overflowCount = computed(() => {
  const arr = (memberAvatars.value || []).filter(Boolean)
  const maxItems = 4
  return arr.length > maxItems ? (arr.length - (maxItems - 1)) : 0
})

// 房主头像首字母（无真实头像则用首字母占位）
const getHostInitial = (creator) => {
  if (!creator || typeof creator !== 'string') return 'U'
  const ch = creator.trim()[0]
  return ch ? ch.toUpperCase() : 'U'
}

// 将房间状态码转换为可读文本
const getStatusText = (status) => {
  const normalizedStatus = status?.toLowerCase()
  switch (normalizedStatus) {
    case 'waiting':
    case 'wait':
      return '等待中'
    case 'playing':
    case 'play':
      return '游戏中'
    case 'finished':
    case 'finish':
      return '已结束'
    default:
      return '未知'
  }
}

// 根据房间状态返回对应的样式类名
const getStatusClass = (status) => {
  const normalizedStatus = status?.toLowerCase()
  switch (normalizedStatus) {
    case 'waiting':
    case 'wait':
      return 'status-waiting'
    case 'playing':
    case 'play':
      return 'status-playing'
    case 'finished':
    case 'finish':
      return 'status-finished'
    default:
      return ''
  }
}

const resolveAvatarUrl = (fileOrUrl) => {
  if (!fileOrUrl) return ''
  if (/^https?:\/\//i.test(fileOrUrl)) return fileOrUrl
  const base = (request?.defaults?.baseURL || '').replace(/\/+$/, '')
  return `${base}/users/avatar-file/${fileOrUrl}`
}

// 如需根据状态切换样式/交互，可在此处扩展状态计算

// 容量进度（0-100）
const occupancyPercent = computed(() => {
  const count = Number(props.room?.playerCount || 0)
  const max = Number(props.room?.maxPlayers || 0)
  if (!max) return 0
  return Math.min(100, Math.round((count / max) * 100))
})

// 进度条渐变色：根据 roomId 稳定取色，避免所有卡片颜色一致
const capacityGradients = [
  'linear-gradient(90deg,#a7f3d0,#10b981)', // 绿
  'linear-gradient(90deg,#fbcfe8,#f472b6)', // 粉
  'linear-gradient(90deg,#fde68a,#f59e0b)', // 橙
  'linear-gradient(90deg,#93c5fd,#3b82f6)', // 蓝
  'linear-gradient(90deg,#c7d2fe,#8b5cf6)', // 紫
  'linear-gradient(90deg,#fca5a5,#ef4444)', // 红
  'linear-gradient(90deg,#6ee7b7,#34d399)', // 青绿
  'linear-gradient(90deg,#fcd34d,#f59e0b)'  // 金黄
]
const computeHash = (value) => {
  const s = String(value || '')
  let h = 0
  for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0
  return h
}
const capacityGradient = computed(() => {
  const key = props.room?.roomId || props.room?.id || props.room?.roomName || 'room'
  const idx = computeHash(key) % capacityGradients.length
  return capacityGradients[idx]
})

const loadHostAvatar = async () => {
  try {
    const roomId = props.room?.roomId || props.room?.id
    if (!roomId) return
    if (hostAvatarCache.has(roomId)) {
      hostAvatar.value = hostAvatarCache.get(roomId)
      // 即便房主头像有缓存，也尝试加载成员头像
    }
    const res = await roomAPI.getRoomInfo(roomId)
    const data = res?.data || res
    const players = Array.isArray(data?.players) ? data.players : []
    let avatar = ''
    if (players.length > 0) {
      const byCreator = players.find(p => (p.username || p.name) === (props.room?.creator || props.room?.owner))
      avatar = byCreator?.avatar || players[0]?.avatar || ''
    }
    const url = resolveAvatarUrl(avatar)
    if (url) {
      hostAvatar.value = url
      hostAvatarCache.set(roomId, url)
    }

    // 收集成员头像（最多 4 个，首个为房主）
    const sorted = []
    if (players.length) {
      const creatorName = props.room?.creator || props.room?.owner
      const creator = players.find(p => (p.username || p.name) === creatorName)
      if (creator) sorted.push(creator)
      for (const p of players) {
        if (creator && (p.id === creator.id)) continue
        sorted.push(p)
      }
    }
    memberAvatars.value = sorted.slice(0, 4).map(p => resolveAvatarUrl(p?.avatar))
  } catch (_) {}
}

onMounted(loadHostAvatar)
watch(() => props.room, loadHostAvatar, { deep: true })
</script>

<template>
  <!-- 房间卡片：点击整卡触发 select 事件，将房间对象传给父组件 -->
  <div class="room-card" @click="emit('select', props.room)">
    <!-- 顶部横幅：封面图（可替换） -->
    <div class="room-main-area">
      <img class="room-cover" :src="coverImg" alt="cover" />
      <!-- 容量进度条（覆盖在封面底部） -->
      <div class="capacity-progress" :aria-label="`占用 ${occupancyPercent}%`">
        <div class="capacity-fill" :style="{ width: occupancyPercent + '%', background: capacityGradient }" />
      </div>
    </div>
    
    <!-- 信息区域：标题行 + 元信息行 -->
    <div class="room-info">
      <div class="title-row">
        <div class="room-name">{{ props.room.roomName || '未命名房间' }}</div>
        <span class="room-status" :class="getStatusClass(props.room.status)">{{ getStatusText(props.room.status) }}</span>
      </div>
      <div class="meta-row">
        <div class="avatar-stack" :title="'成员头像（首个为房主）'">
          <span v-for="(av, i) in (displayedAvatars.length ? displayedAvatars : [hostAvatar])" :key="'av-'+i" class="stack-item" :class="{ host: i === 0 }">
            <img v-if="av" :src="av" alt="avatar" />
            <span v-else>{{ i === 0 ? getHostInitial(props.room.creator) : '' }}</span>
          </span>
          <span v-if="overflowCount > 0" class="stack-item more">+{{ overflowCount }}</span>
        </div>
        <span class="player-chip">{{ props.room.playerCount || 0 }}/{{ props.room.maxPlayers || 5 }}</span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.room-card {
  background: #ffffff;
  border: 1px solid #eef2f7;
  border-radius: 16px;
  cursor: pointer;
  transition: transform .18s ease, box-shadow .18s ease, border-color .18s ease;
  display: flex;
  flex-direction: column;
  min-height: 220px;
  overflow: hidden;
  box-shadow: 0 6px 16px rgba(2,6,23,0.06);
}

.room-card:hover { border-color: #c7d2fe; box-shadow: 0 14px 28px rgba(37,99,235,0.16); transform: translateY(-3px); }

/* 主展示区域 */
.room-main-area {
  flex: 1;
  background: linear-gradient(180deg, #f1f5f9 0%, #e9eef5 100%);
  min-height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.room-cover { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; opacity: .9; }
.room-main-area::after { content: ''; position: absolute; inset: 0; background: radial-gradient(ellipse at 30% 70%, rgba(255,255,255,.08), transparent 60%), radial-gradient(ellipse at 80% 20%, rgba(255,255,255,.06), transparent 60%); }

/* 容量进度条覆盖在封面底部 */
.capacity-progress { position: absolute; left: 0; right: 0; bottom: 0; height: 6px; background: #eef2f7; }
.capacity-fill { height: 100%; background: linear-gradient(90deg,#93c5fd,#3b82f6); transition: width .25s ease; }

/* 信息区域布局 */
.room-info { padding: 14px 16px 16px; background: #fff; border-top: 1px solid #f1f5f9; }
.title-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
.room-name { font-size: 18px; font-weight: 800; color: #0f172a; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1.2; letter-spacing: .2px; }
.meta-row { display: flex; align-items: center; gap: 10px; color: #475569; font-size: 13px; }

.avatar-stack { display: inline-flex; align-items: center; }
.stack-item {
  width: 26px;
  height: 26px;
  border-radius: 999px;
  background: linear-gradient(180deg,#e5e7eb,#f3f4f6);
  color: #111827;
  font-weight: 800;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 1px 0 rgba(0,0,0,.04);
  border: 1px solid #e5e7eb;
  margin-left: -8px;
  overflow: hidden;
}
.stack-item:first-child { margin-left: 0; }
.stack-item.host { outline: 2px solid #fde68a; box-shadow: 0 0 0 2px #fde68a inset; }
.stack-item img { width: 100%; height: 100%; border-radius: 999px; display: block; }
.stack-item.more { background: #e2e8f0; color: #0f172a; font-size: 11px; font-weight: 900; letter-spacing: .2px; }

.player-chip { font-weight: 700; color: #065f46; background: #d1fae5; padding: 4px 10px; border-radius: 999px; font-size: 12px; border: 1px solid #a7f3d0; }

@media (max-width: 640px) {
  .room-card { border-radius: 12px; min-height: 200px; }
  .room-main-area { min-height: 120px; }
  .room-name { font-size: 16px; }
}

.room-info-right { display: flex; flex-direction: column; align-items: flex-end; }
.room-status { font-size: 12px; padding: 6px 12px; border-radius: 999px; font-weight: 700; letter-spacing: 0.3px; box-shadow: 0 2px 4px rgba(0,0,0,0.06); border: 1px solid transparent; }

/* 状态标签样式：等待 / 进行中 / 已结束 */
.status-waiting { background: #eef2ff; color: #3730a3; border-color: #c7d2fe; }
.status-playing { background: #ecfdf5; color: #065f46; border-color: #a7f3d0; }
.status-finished { background: #fee2e2; color: #991b1b; border-color: #fecaca; }

/* 进入按钮已移除 */
</style>